package com.quick.calcu.service.impl;

import com.quick.calcu.entity.Student;
import com.quick.calcu.entity.Teacher;
import com.quick.calcu.entity.User;
import com.quick.calcu.mapper.UserMapper;
import com.quick.calcu.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;

@Service
@Transactional // 添加事务管理
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper; // MyBatis Mapper
//    @Autowired
//    private StudentService studentService;  // 学生表对应的 Service
//
//    @Autowired
//    private TeacherService teacherService;  // 教师表对应的 Service

//    private boolean registerStudent(User user) {
//        // 你可以在这里初始化学生角色特有数据
//        // 例如插入 student_info 表（如果你有）
//        boolean userSaved = save(user);  // 保存用户基本信息
//        if (!userSaved) {
//            return false;
//        }
//
//        // 假设你有个 Student 实体，里面有 userId 字段关联 User
//        Student student = new Student();
//        student.setUserId(user.getUserId());  // 关联刚插入的用户ID
//        student.setStudentName(user.getUsername());
//        // 你可以设置学生特有的字段，比如班级等
//        // student.setClassId(...);
//
//        boolean studentSaved = studentService.save(student);
//        return studentSaved;
//    }
//
//    private boolean registerTeacher(User user) {
//        // 教师角色注册逻辑
//        boolean userSaved = save(user);
//        if (!userSaved) {
//            return false;
//        }
//
//        Teacher teacher = new Teacher();
//        teacher.setUserId(user.getUserId());
//        teacher.setTeacherName(user.getUsername());
//        // 设置教师特有字段
//
//        boolean teacherSaved = teacherService.save(teacher);
//        return teacherSaved;
//    }


    @Override
    public boolean register(User user) {
        // 1. 校验：用户名/密码非空
        if (user.getUsername() == null || user.getPassword() == null) {
            throw new IllegalArgumentException("用户名或密码不能为空");
        }

        // 2. 检查用户名是否重复
        User existUser = lambdaQuery()
                .eq(User::getUsername, user.getUsername())
                .one();
        if (existUser != null) {
            throw new IllegalArgumentException("用户名已存在");
        }

        // 3. 判断类型并执行不同逻辑
        if (user.getUserType() == null) {
            throw new IllegalArgumentException("用户类型不能为空");
        }

//        switch (user.getUserType()) {
//            case 1:
//                return registerStudent(user);
//            case 2:
//                return registerTeacher(user);
//            default:
//                throw new IllegalArgumentException("不支持的用户类型: " + user.getUserType());
//        }
        return save(user);
    }

    @Override
    @Transactional(readOnly = true)
    public User login(String username, String password) {
        // 1. 查询用户
        User user = lambdaQuery()
                .eq(User::getUsername, username)
                .one();
        if (user == null) {
            return null;
//            throw new IllegalArgumentException("用户不存在");
        }

        // 2. 校验密码
        // 直接比较明文密码（不加密）
        if (!password.equals(user.getPassword())) {
            user.setPassword(null);
            return user;
//            throw new IllegalArgumentException("密码错误");
        }

        return user;
    }

    @Override
    public List<User> listByType(Integer userType) {
        if (userType == null) {
            return list();
        }
        return lambdaQuery()
                .eq(User::getUserType, userType)
                .list();
    }

    @Override
    @Transactional
    public boolean updatePassword(Long userId, String oldPassword, String newPassword) {
        // 1. 查询用户
        User user = getById(userId);
        if (user == null) {
            throw new IllegalArgumentException("用户不存在");
        }

        // 2. 校验旧密码
        // 直接比较明文密码（不加密）
        if (!oldPassword.equals(user.getPassword())) {
            throw new IllegalArgumentException("密码错误");
        }

        // 3. 新密码更新
        user.setPassword(newPassword);
        return updateById(user);
    }

    @Override
    public boolean existsByUsername(String username) {
        return userMapper.countByUsername(username) > 0;
    }
}